import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Tabs, Empty, Badge,Tag} from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getOrders } from '../../utils/storage';
import { orderAPI } from '../../services/api';
import { message } from '../../utils/message';
import './Orders.css';

const { TabPane } = Tabs;

const Orders = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [orders, setOrders] = useState([]);
  const [activeTab, setActiveTab] = useState('all');
  const [loading, setLoading] = useState(false);
  const [afterSales, setAfterSales] = useState([]);  // 新增售后数据状态

  useEffect(() => {
    loadOrders();
    // 加载售后数据
    const afterSalesData = JSON.parse(localStorage.getItem('afterSales') || '[]');
    console.log('加载的售后数据:', afterSalesData); // 添加调试日志
    setAfterSales(afterSalesData);
    // 从URL参数获取状态
    const status = searchParams.get('status');
    if (status) {
      setActiveTab(status);
    }
  }, [searchParams]);

  useEffect(() => {
    // 监听页面可见性变化，当页面重新可见时刷新订单数据
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        loadOrders();
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  const loadOrders = () => {
    const userOrders = getOrders();
    // 按创建时间倒序排列
    const sortedOrders = userOrders.sort((a, b) => b.createTime - a.createTime);
    setOrders(sortedOrders);
  };

  const getFilteredOrders = (status) => {
    if (status === 'all') return orders;
    if (status === 'aftersales') {
      // 获取所有有售后记录的订单
      const afterSaleOrderIds = afterSales.map(as => as.orderId);
      console.log('售后订单ID列表:', afterSaleOrderIds);
      console.log('当前所有订单:', orders);
      // 确保类型一致进行比较
      const filteredOrders = orders.filter(order => 
        afterSaleOrderIds.includes(order.id.toString())
      );
      console.log('过滤后的售后订单:', filteredOrders);
      return filteredOrders;
    }
    return orders.filter(order => order.status === status);
  };

  const getStatusText = (status) => {
    const statusMap = {
      pending: '待付款',
      paid: '待发货',
      shipped: '运输中',
      delivered: '已收货',
      cancelled: '已取消',
      refund: '退款中'
    };
    return statusMap[status] || status;
  };

  const getStatusColor = (status) => {
    const colorMap = {
      pending: '#faad14',
      paid: '#1890ff',
      shipped: '#52c41a',
      delivered: '#52c41a',
      cancelled: '#d9d9d9',
      refund: '#ff4d4f'
    };
    return colorMap[status] || '#d9d9d9';
  };

  const handleOrderClick = (order) => {
    // 如果在售后标签页并且订单有售后记录，直接跳转到售后详情
    if (activeTab === 'aftersales') {
      const orderAfterSale = afterSales.find(as => as.orderId === order.id.toString());
      if (orderAfterSale) {
        navigate(`/app/after-sale/${orderAfterSale.id}`);
        return;
      }
    }
    // 其他情况跳转到订单详情
    navigate(`/app/order/${order.id}`);
  };

  const handlePayOrder = async (e, order) => {
    e.stopPropagation();
    setLoading(true);
    
    try {
      // 跳转到支付页面
      navigate('/app/payment', {
        state: {
          orderId: order.id,
          orderData: {
            ...order,
            fromCart: false
          }
        }
      });
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleViewLogistics = (e, order) => {
    e.stopPropagation();
    navigate(`/app/order/${order.id}`);
  };

  const handleConfirmReceive = async (e, order) => {
    e.stopPropagation();
    setLoading(true);
    
    try {
      const response = await orderAPI.updateOrderStatus(order.id, 'delivered');
      if (response.success) {
        message.success('确认收货成功');
        loadOrders();
      }
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReview = (e, order) => {
    e.stopPropagation();
    message.info('评价功能开发中');
  };

  const renderOrderItem = (order) => {
    // 查找当前订单的售后记录
    const orderAfterSale = afterSales.find(as => as.orderId === order.id);
    
    return (
      <div key={order.id} className="order-item" onClick={() => handleOrderClick(order)}>
        <div className="order-header">
          <span className="order-no">订单号：{order.orderNo}</span>
          {activeTab === 'aftersales' ? (
            orderAfterSale && (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {orderAfterSale.status === 'PENDING' && <Tag color="orange">待审核</Tag>}
                {orderAfterSale.status === 'APPROVED' && <Tag color="green">等待用户退货</Tag>}
                {orderAfterSale.status === 'RETURNING' && <Tag color="blue">退货中，等待商家确认收货</Tag>}
                {orderAfterSale.status === 'REFUNDED' && <Tag color="purple">退货成功，已退款</Tag>}
                {orderAfterSale.status === 'REJECTED' && <Tag color="red">已驳回</Tag>}
              </div>
            )
          ) : (
            <>
              <Badge 
                color={getStatusColor(order.status)}
                text={getStatusText(order.status)}
              />
              {orderAfterSale && (
                <div style={{ marginLeft: '8px' }}>
                  {orderAfterSale.status === 'PENDING' && <Tag color="orange">待审核</Tag>}
                  {orderAfterSale.status === 'APPROVED' && <Tag color="green">等待用户退货</Tag>}
                  {orderAfterSale.status === 'RETURNING' && <Tag color="blue">退货中，等待商家确认收货</Tag>}
                  {orderAfterSale.status === 'REFUNDED' && <Tag color="purple">退货成功，已退款</Tag>}
                  {orderAfterSale.status === 'REJECTED' && <Tag color="red">已驳回</Tag>}
                </div>
              )}
            </>
          )}
        </div>
        
        <div className="order-products">
          {order.products.map((product, index) => (
            <div key={index} className="order-product">
              <img 
                src={product.images[0]} 
                alt={product.name}
                className="product-image"
              />
              <div className="product-info">
                <div className="product-name">{product.name}</div>
                {product.selectedSpecs && (
                  <div className="product-specs">
                    {Object.entries(product.selectedSpecs).map(([key, value]) => (
                      <span key={key}>{key}: {value} </span>
                    ))}
                  </div>
                )}
                <div className="product-price-qty">
                  <span className="price">¥{product.price}</span>
                  <span className="quantity">x{product.quantity}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
        
        <div className="order-footer">
          <div className="order-total">
            共{order.products.reduce((sum, p) => sum + p.quantity, 0)}件商品 
            实付 <span className="total-amount">¥{order.totalAmount.toFixed(2)}</span>
          </div>
          <div className="order-actions">
            {order.status === 'pending' && (
              <Button 
                size="small" 
                type="primary"
                loading={loading}
                onClick={(e) => handlePayOrder(e, order)}
              >
                去支付
              </Button>
            )}
            {order.status === 'shipped' && (
              <>
                <Button 
                  size="small"
                  style={{ marginRight: '8px' }}
                  onClick={(e) => handleViewLogistics(e, order)}
                >
                  查看物流
                </Button>
                <Button 
                  size="small" 
                  type="primary"
                  loading={loading}
                  onClick={(e) => handleConfirmReceive(e, order)}
                >
                  确认收货
                </Button>
              </>
            )}
            {order.status === 'delivered' && (
              <Button 
                size="small"
                onClick={(e) => handleReview(e, order)}
              >
                评价
              </Button>
            )}
          </div>
        </div>
        
        <div className="order-time">
          下单时间：{new Date(order.createTime).toLocaleString()}
        </div>
      </div>
    );
  };

  const renderOrderList = (status) => {
    const filteredOrders = getFilteredOrders(status);
    
    if (filteredOrders.length === 0) {
      return (
        <div style={{ padding: '40px 16px', textAlign: 'center' }}>
          <Empty 
            description="暂无订单"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        </div>
      );
    }

    return (
      <div className="orders-list">
        {filteredOrders.map(renderOrderItem)}
      </div>
    );
  };

  return (
    <div className="orders-page">
      {/* 头部导航 */}
      <div className="orders-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">我的订单</span>
      </div>

      {/* 订单状态标签 */}
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        className="order-tabs"
      >
        <TabPane tab="全部" key="all">
          {renderOrderList('all')}
        </TabPane>
        <TabPane tab="待付款" key="pending">
          {renderOrderList('pending')}
        </TabPane>
        <TabPane tab="待发货" key="paid">
          {renderOrderList('paid')}
        </TabPane>
        <TabPane tab="待收货" key="shipped">
          {renderOrderList('shipped')}
        </TabPane>
        <TabPane tab="已完成" key="delivered">
          {renderOrderList('delivered')}
        </TabPane>
        <TabPane tab="退款/售后" key="aftersales">
          {renderOrderList('aftersales')}
        </TabPane>
      </Tabs>
    </div>
  );
};

export default Orders; 